from django.http import HttpResponse
from django.shortcuts import render_to_response
from polls.models import Poll, Choice
from django.http import Http404
from StartGroup.models import Group
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django import forms
from polls.models import PollForm, ChoiceForm
from django.http import QueryDict
from django.conf import settings
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from utils import activity_module, common_query, common_methods
from connectpeople import Constants
import threading

def index(request, group_web_address):
    group = Group.objects.get(group_web_address=group_web_address)
    latest_poll_list = Poll.objects.filter(group_web_address=group_web_address).order_by('-pub_date')
    data = {}
    index_data = []
    for each in latest_poll_list:
        item = []
        votes = 0
        response = 0
        c = Choice.objects.filter(poll=each)
        for i in c:
                response = i.votes
                votes =  votes + i.votes 
                item.append((i.choice, response))        
        data[each.poll_topic] = item
        index_data.append((each, votes, item))
    paginator = Paginator(index_data, 5)
        
    # Make sure page request is an int. If not, deliver first page.
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    # If page request (9999) is out of range, deliver last page of results.
    try:
        pages = paginator.page(page)
    except (EmptyPage, InvalidPage):
        pages = paginator.page(paginator.num_pages)
    
    # Obtain user id
    userid = request.session[Constants.session_userid]    
    
    # Get User object with permissions assigned
    permission = common_query.get_user_group_permission(userid, group_web_address, False)
    
    return render_to_response('polls/index.html',
                {'poll_pages': pages,'group':group, 'permission':permission })

def detail(request, poll_id, group_web_address):
    
    # Obtain user id
    userid = request.session[Constants.session_userid]    
    
    # Get User object with permissions assigned
    permission = common_query.get_user_group_permission(userid, group_web_address, False)    
    
    try:
        p = Poll.objects.get(pk=poll_id)
    except Poll.DoesNotExist:
        raise Http404
    return render_to_response('polls/details.html', {'poll': p, 'permission':permission})


def results(request, poll_id, group_web_address):
    return HttpResponse("You're looking at the results of poll %s." % poll_id)

def vote(request, poll_id, group_web_address):
    group_web_addr = group_web_address
    group = Group.objects.get(group_web_address=group_web_addr)
    userid = request.session[Constants.session_userid]
    
    # Get User object with permissions assigned
    permission = common_query.get_user_group_permission(userid, group_web_address, False)    
    
    p = Poll.objects.get(id=poll_id)
    c = Choice.objects.filter(poll=p)
    poll_topic = p.poll_topic
    choice = []
    for i in c:
        choice.append((i.choice, i))
    ChoiceFormClass = ChoiceForm(('poll', 'choice'))
    ChoiceFormClass.fields['votes'] = forms.CharField(label=poll_topic, widget=forms.widgets.RadioSelect(choices=choice))
    ChoiceFormClass.fields['votes'].required = True
        
    if request.POST:
        ChoiceFormClass = ChoiceForm(('poll', 'choice'), request.POST)
        ChoiceFormClass.fields['votes'] = forms.CharField(label=poll_topic, widget=forms.widgets.RadioSelect(choices=choice))
        ChoiceFormClass.fields['votes'].required = True
        bound = ChoiceFormClass.is_bound
        valid = ChoiceFormClass.choice_validation(bound)
        if valid:
            c = c.get(choice=request.POST.__getitem__('votes'))
            v = c.votes
            c.votes = v + 1
            c.save()
            
            # New Vote Activity save 
            activity_module.setActivityNode(p.poll_topic, userid, group_web_addr, Constants.poll_voted_action)                
            
            # Get email ids of these users
            recipient_list = common_query.getGroupMembersEmailIds(group_web_addr, Constants.new_vote_email_flag_constant)             
            
            # Compose subject for the email
            subj = p.poll_topic + " - New Vote posted"
            # Send Email alerts. Use threading to speed up things
            new_comment_thread= threading.Thread(target=common_methods.send_email_helper, kwargs={'a_sender':Poll, 'a_email':recipient_list, 'a_model':p, 'a_subject':subj, 'a_template':"email/newVoteEmail.html"})
            new_comment_thread.setDaemon(True)
            new_comment_thread.start()              
            
            return HttpResponseRedirect('../../')
        else:
            
            return render_to_response('polls/vote.html', {'vote_form': ChoiceFormClass, 'group':group }, context_instance=RequestContext(request))
    else:
        error_messages = 'Please Select an Option'
        return render_to_response('polls/vote.html', {'vote_form': ChoiceFormClass, 'group':group, 'error_messages': error_messages,
                                                      'permission':permission}, context_instance=RequestContext(request))

def add_poll(request, group_web_address):
    group_web_addr = group_web_address
    group = Group.objects.get(group_web_address=group_web_addr)
    userid = request.session[Constants.session_userid]
    
    # Get User object with permissions assigned
    permission = common_query.get_user_group_permission(userid, group_web_address, False)    
    
    PollFormClass = PollForm(('group_web_address', 'pub_date', 'status'))
    PollFormClass.fields['poll_topic'] = forms.CharField(error_messages={'required': 'Please Enter the Poll Topic.'}, widget=forms.widgets.TextInput(attrs={'size':'25'}))
    PollFormClass.fields['poll_topic'].required = True
    PollFormClass.fields['choice_count'] = forms.CharField(widget=forms.widgets.HiddenInput(), initial=settings.NO_OF_CHOICES)
    choice_forms = []
    choice_object_list = []
    if request.POST:
        PollFormClass = PollForm(('group_web_address', 'pub_date','status'), data=request.POST)
        PollFormClass.fields['poll_topic'] = forms.CharField(error_messages={'required': 'Please Enter the Poll Topic.'}, widget=forms.widgets.TextInput(attrs={'size':'25'}))
        PollFormClass.fields['poll_topic'].required = True
        PollFormClass.fields['choice_count'] = forms.CharField(widget=forms.widgets.HiddenInput(), initial=settings.NO_OF_CHOICES)
        group = Group.objects.get(group_web_address=group_web_addr)
        poll_form_valid = PollFormClass.is_valid()
        if poll_form_valid:
            poll = PollFormClass.save(commit=False)
            poll.group_web_address = group
            poll.status = 0
        choice_list = request.POST.getlist('choice')
        qc = QueryDict('choice')
        qc = qc.copy()
        for i in range(int(request.POST['choice_count'])):
            qc.update({'choice' : choice_list[i]})
            ChoiceFormClass = ChoiceForm(('votes', 'poll'), qc)
            ChoiceFormClass.fields['choice'] = forms.CharField(error_messages={'required': 'Please Enter the choice %s.' % (i+1)}, widget=forms.widgets.TextInput(attrs={'size':'25'}))
            ChoiceFormClass.fields['choice'].required = True
                
            choice_form_valid = ChoiceFormClass.is_valid()   
            if choice_form_valid:
                choice = ChoiceFormClass.save(commit=False)
                choice_object_list.append(choice)
            choice_forms.append(ChoiceFormClass)
        
        if not poll_form_valid or not choice_form_valid:
            return render_to_response('polls/createpoll.html', {'poll_form': PollFormClass, 'group':group, 'choice_forms': choice_forms,'permission':permission}, context_instance=RequestContext(request))    
        
        else:
            poll.save()
            for choice_instance in choice_object_list:
                choice_instance.poll = poll
                choice_instance.votes = 0
                choice_instance.save()
                
            # New Poll Activity save 
            activity_module.setActivityNode(poll.poll_topic, userid, group_web_addr, Constants.create_poll_action)
            
            # Get email ids of these users
            recipient_list = common_query.getGroupMembersEmailIds(group_web_addr, Constants.new_poll_email_flag_constant)            
            
            # Compose subject for the email
            subj = poll.poll_topic + " - New Poll created"
            # Send Email alerts. Use threading to speed up things
            new_comment_thread= threading.Thread(target=common_methods.send_email_helper, kwargs={'a_sender':Poll, 'a_email':recipient_list, 'a_model':poll, 'a_subject':subj, 'a_template':"email/createPollEmail.html"})
            new_comment_thread.setDaemon(True)
            new_comment_thread.start()            
            
            return HttpResponseRedirect('../')
    else:
        for i in range(settings.NO_OF_CHOICES):
            ChoiceFormClass = ChoiceForm(('choice'))
            ChoiceFormClass.fields['choice'] = forms.CharField(error_messages={'required': 'Please Enter the choice %s.' % (i+1)}, widget=forms.widgets.TextInput(attrs={'size':'25'}))
            ChoiceFormClass.fields['choice'].required = True
            choice_forms.append(ChoiceFormClass)
        return render_to_response('polls/createpoll.html', {'poll_form': PollFormClass, 'group':group, 'choice_forms': choice_forms,'permission':permission}, context_instance=RequestContext(request))